package cn.com.dcsgo.mybatis.plus.service.impl;

import cn.com.dcsgo.mybatis.plus.mapper.UserMapper;
import cn.com.dcsgo.mybatis.plus.domain.po.User;
import cn.com.dcsgo.mybatis.plus.service.UserService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Dcsgo
 * @since 2024/8/28 10:31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public boolean increaseBalance(Long id, int increment) {
        return baseMapper.updateBalanceByWrapper(increment,
                new LambdaUpdateWrapper<User>().eq(User::getId, id)) >= 1;
    }

    @Transactional
    @Override
    public void reduceBalance(Long id, Integer money) {
        User user = getById(id);
        if (user == null || user.getStatus() != 1) {
            throw new IllegalArgumentException("用户不存在或用户状态异常");
        }
        if (user.getBalance() < money) {
            throw new IllegalArgumentException("用户余额不足");
        }
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance())//乐观锁
                .update();//执行更新操作
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }
}
